package com.daguchuangyi.erp_android.productlist.scan;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.daguchuangyi.erp_android.R;
import com.daguchuangyi.erp_android.base.TransStatusBarActivity;
import com.daguchuangyi.erp_android.manager.NetworkManager;
import com.daguchuangyi.erp_android.manager.networkservice.ProductService;
import com.daguchuangyi.erp_android.production_detail.ProductDetailActivity;
import com.daguchuangyi.erp_android.util.ErrorHandler;
import com.daguchuangyi.erp_android.util.FileUtil;
import com.jude.utils.JUtils;
//import com.uuzuche.lib_zxing.activity.CaptureFragment;
//import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.util.HashMap;
import java.util.Map;

import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

public class ScanActivity extends TransStatusBarActivity implements View.OnClickListener {
    private static final String TAG = ScanActivity.class.getSimpleName();

    private static final int REQUEST_IMAGE = 0x1;

    private TextView mGalleryTv;
    private TextView mCancelTv;
    private TextView mDoneTv;
//    private CaptureFragment mCaptureFragment;

    private CompositeSubscription mCompositeSubscription = new CompositeSubscription();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan);

        mGalleryTv = (TextView) findViewById(R.id.gallery_tv);
        mGalleryTv.setOnClickListener(this);
        mCancelTv = (TextView) findViewById(R.id.cancel_tv);
        mCancelTv.setOnClickListener(this);
        mDoneTv = (TextView) findViewById(R.id.done_tv);
        mDoneTv.setOnClickListener(this);

//        mCaptureFragment = new CaptureFragment();
//        CodeUtils.setFragmentArgs(mCaptureFragment, R.layout.my_camera);
//        mCaptureFragment.setAnalyzeCallback(this);
//        getSupportFragmentManager().beginTransaction().replace(R.id.fl_my_container, mCaptureFragment).commit();
    }

//    @Override
//    public void onAnalyzeSuccess(Bitmap mBitmap, String result) {
//        JUtils.Log("result is : " + result);
//        String[] results = result.split("\\n");
//        if (results.length > 1) {
//            String firstLine = result.split("\\n")[0];
//            String productSerialNum = firstLine.split(":")[1];
//            JUtils.Log("product serical num is : " + productSerialNum);
//            loadProduct(productSerialNum);
//        } else {
//            loadProduct(result);
//        }
//    }

    private void loadProduct(String productSerialNum) {
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("PNO", productSerialNum);
        Subscription subscription = NetworkManager.getInstance().getRetrofit().create(ProductService.class)
                .getProductDetailByPNO(queryMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(productWrapper -> {
                    JUtils.Log("load product detail successfully.");
                    ProductDetailActivity.start(ScanActivity.this, productWrapper.getProduct().getId());
                    finish();
                }, throwable -> {
//                    Message obtain = Message.obtain();
//                    obtain.what = R.id.restart_preview;
//                    mCaptureFragment.getHandler().sendMessageDelayed(obtain, 1500);
                    ErrorHandler.handlerNetworError(throwable, "加载失败，请检查网络状态");
                    throwable.printStackTrace();
                });
        mCompositeSubscription.add(subscription);
    }

//    @Override
//    public void onAnalyzeFailed() {
//        JUtils.Log("识别失败");
//        JUtils.Toast("未找到识别码，请重试");
//    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.cancel_tv:
            case R.id.done_tv:
                finish();
                break;
            case R.id.gallery_tv:
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("image/*");
                startActivityForResult(intent, REQUEST_IMAGE);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE) {
            if (data != null) {
                try {
                    Uri uri = data.getData();
                    String path = FileUtil.getFilePathByUri(this, uri);
                    Log.i(TAG, "image path is : " + path);
//                    CodeUtils.analyzeBitmap(path, this);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        mCompositeSubscription.clear();
        super.onDestroy();
    }
}
